package luke4fun.wheresmymoney.service.async;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;

import java.util.ArrayList;
import java.util.List;

import luke4fun.wheresmymoney.adapter.list.BasicAdapter;
import luke4fun.wheresmymoney.bean.AccBean;
import luke4fun.wheresmymoney.bean.AccDtlBean;
import luke4fun.wheresmymoney.bean.DayAccBean;
import luke4fun.wheresmymoney.common.CommonConstants;
import luke4fun.wheresmymoney.db.AccDBHelper;
import luke4fun.wheresmymoney.db.DBConstants;

public class HomeAsyncTask extends AsyncTask<Integer, String, List<AccBean>> {
	private SQLiteDatabase db;
	private AccDBHelper dbHelper;
	private BasicAdapter<AccBean> adapter;
	private long timeInMillis;
	
	public HomeAsyncTask(Context context, BasicAdapter<AccBean> adapter, long timeInMillis) {
		dbHelper = new AccDBHelper(context);
		this.adapter = adapter;
		this.timeInMillis = timeInMillis;
	}
	
	@Override
	protected List<AccBean> doInBackground(Integer... params) {
		List<AccBean> beanList = new ArrayList<AccBean>(0);
		
		String[] interval = new String[] { timeInMillis + "", (timeInMillis + CommonConstants.ONE_DAY) + ""};

		db = dbHelper.getReadableDatabase();
		Cursor cursor = db.query(DBConstants.V_RECORD, 
								null, 
								DBConstants.RECORD_DATATIME + " >= ? AND " + DBConstants.RECORD_DATATIME + " < ?", 
								interval, 
								null, 
								null, 
								DBConstants.RECORD_ID);

		DayAccBean bean = new DayAccBean();
		while (cursor.moveToNext()) {
			Long id 		= cursor.getLong(cursor.getColumnIndex(DBConstants.RECORD_ID));
			Long pid 		= cursor.getLong(cursor.getColumnIndex(DBConstants.RECORD_PID));
			String item 	= cursor.getString(cursor.getColumnIndex(DBConstants.RECORD_ITEM));
			String category = cursor.getString(cursor.getColumnIndex(DBConstants.RECORD_CATEGORY));
			Integer price = null;
			
			int index = cursor.getColumnIndex(DBConstants.RECORD_PRICE);
			if (!cursor.isNull(index)) {
				price = cursor.getInt(cursor.getColumnIndex(DBConstants.RECORD_PRICE));
			}
			
			AccBean acc = bean.getAccMap().get(category);
			if (acc == null) {
				acc = new AccBean();
				acc.setCategory(category);
			}
			
			AccDtlBean dtl = new AccDtlBean();
			dtl.setId(id);
			dtl.setPid(pid);
			dtl.setItem(item);
			dtl.setPrice(price);
			
			if (pid == -1) {
				acc.putDtl(id, dtl);
				acc.setSum(acc.getSum() + price);
			}
			else {
				acc.getDtl(pid).getInfoList().add(dtl);
			}
			
			// put into acc map by category
			bean.getAccMap().put(category, acc);
		}
		
		beanList.addAll(bean.getAccMap().values());
		
		db.close();
		dbHelper.close();
		return beanList;
	}
	
	@Override
	protected void onPostExecute(List<AccBean> result) {
		adapter.updateList(result);
	}
}
